<template>
  <div class="divBox">
    <el-card class="box-card">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm" v-loading="loading">
        <el-form-item label="优惠劵名称" prop="name">
          <el-input v-model="ruleForm.name" style="width: 350px" placeholder="请输入优惠券名称"></el-input>
        </el-form-item>
        <el-form-item label="优惠劵类型" prop="useType">
          <el-radio-group v-model="ruleForm.useType">
            <el-radio :label="0">通用券</el-radio>
            <el-radio :label="1">商品券</el-radio>
            <el-radio :label="3">品类券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择品类：" prop="primaryKey" v-if="ruleForm.useType === 3">
          <el-cascader v-model="ruleForm.primaryKey" :options="merCateList" :props="props2" clearable class="selWidth" :show-all-levels="false" />
        </el-form-item>
        <el-form-item label="商品：" v-if="ruleForm.useType === 1" prop="checked">
          <div class="acea-row">
            <template v-if="ruleForm.checked.length">
              <div class="pictrue" v-for="(item, index) in ruleForm.checked" :key="index">
                <img :src="item.cover">
                <i class="el-icon-error btndel" @click="handleRemove(index)" />
              </div>
            </template>
            <div class="upLoadPicBox" @click="changeGood">
              <div class="upLoad">
                <i class="el-icon-camera cameraIconfont" />
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="优惠券面值" prop="money">
          <el-input-number v-model="ruleForm.money" :min="1" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="使用门槛">
          <el-radio-group v-model="ruleForm.menkan">
            <el-radio :label="false">无门槛</el-radio>
            <el-radio :label="true">有门槛</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠券最低消费" prop="minPrice" v-if="ruleForm.menkan">
          <el-input-number v-model="ruleForm.minPrice" :min="1" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="使用有效期" prop="fixedTime">
          <el-radio-group v-model="ruleForm.fixedTime">
            <el-radio :label="false">天数</el-radio>
            <el-radio :label="true">时间段</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用有效期限（天）" prop="day" v-if="!ruleForm.fixedTime">
          <el-input-number v-model="ruleForm.day" :min="0" :max="999" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="使用有效期限" prop="time" v-if="ruleForm.fixedTime">
          <el-date-picker
            style="width: 550px"
            v-model="ruleForm.time"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            :picker-options="pickerOptions"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="代金券开始时间" prop="revetime">
          <el-date-picker
            style="width: 550px"
            v-model="ruleForm.revetime"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领取方式" prop="resource">
          <el-radio-group v-model="ruleForm.type">
            <el-radio :label="0">手动领取</el-radio>
            <el-radio :label="1">注册券</el-radio>
            <el-radio :label="2">赠送券</el-radio>
            <!--<el-radio :label="4">付费会员卷</el-radio>-->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否限量" prop="limitness">
          <el-radio-group v-model="ruleForm.limitness">
            <el-radio :label="true">限量</el-radio>
            <el-radio :label="false">不限量</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布数量" prop="total" v-if="ruleForm.limitness">
          <el-input-number v-model="ruleForm.total" :min="1" label="排序"></el-input-number>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="ruleForm.sort" :min="0" label="排序"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="submitForm('ruleForm')" :loading="loading" v-hasPermi="['admin:coupon:save']">立即创建</el-button>
          <!--<el-button @click="resetForm('ruleForm')">重置</el-button>-->
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog  :visible.sync="modals" title="商品列表" footerHide  class="paymentFooter" scrollable width="900" @on-cancel="cancel" style="height:800px">
         <GoodList ref="Goodslist" @getStoreItem="getStoreItem" :handleNum="handleNum" :skushow='true'/>
    </el-dialog>
  </div>
</template>

<script>
import GoodList from '@/components/goodList'
  import { couponSaveApi, couponInfoApi } from '@/api/marketing'
  import { categoryApi } from '@/api/store'
  import {Debounce} from '@/utils/validate'
  export default {
    name: "creatCoupon",
    components: {GoodList },
    data() {
      return {
        modals:false,
        handleNum:'many',
        pickerOptions: {
          disabledDate(time) {
            // return time.getTime() < new Date().setTime(new Date().getTime() - 3600 * 1000 * 24); //不限制未来时间
            return time.getTime() < Date.now() - 8.64e7 || time.getTime() > Date.now() + 600 * 8.64e7; //限制未来时间
          }
        },
        loading: false,
        threshold: false,
        props2: {
          children: 'child',
          label: 'name',
          value: 'id',
          checkStrictly: true,
          emitPath: false
        },
        couponType: 0,
        term: 'termday',
        merCateList: [], // 商户分类筛选
        ruleForm: {
          useType: 1,
          fixedTime: false,
          name: '',
          money: 1,
          minPrice: 1,
          day: null,
          isForever: false,
          primaryKey: '',
          type: 2,
          limitness: false,
          useStartTime: '', // 使用
          useEndTime: '', // 结束
          receiveStartTime: '', //领取
          receiveEndTime: '',
          sort: 0,
          total: 1,
          status: 0,
          checked: [],
          menkan:false,
          time:[],
          caseIds:'',
        },
        isForeverTime: [],
        rules: {
          name: [
            { required: true, message: '请输入优惠券名称', trigger: 'blur' }
          ],
          day: [
            { required: true, message: '请输入使用有效期限（天）', trigger: 'blur' }
          ],
          money: [
            { required: true, message: '请输入优惠券面值', trigger: 'blur' }
          ],
          primaryKey: [
            { required: true, message: '请选择品类', trigger: 'change' }
          ],
          checked:  [
            { required: true, message: '请至少选择一个商品', trigger: 'change', type: 'array' }
          ],
          isForeverTime: [
            { required: true, message: '请选择领取时间', trigger: 'change', type: 'array' }
          ],
          total: [
            { required: true, message: '请输入发布数量', trigger: 'blur' }
          ],
          minPrice: [
            { required: true, message: '请输入最低消费', trigger: 'blur' }
          ],
          revetime:[
          { required: true, message: "请选择代金券开始日期", trigger: "blur" },
        ],
        time: [{ required: true, message: "使用有效期", trigger: "blur" }],
        }
      }
    },
    mounted() {
      this.getCategorySelect()
      if( this.$route.params.id ) this.getInfo()
    },
    methods: {
      //商品弹窗
    changeGood(){
         this.modals=true
      },
    //商品
      cancel () {
                this.modals = false;
            },
      // 商品分类；
      getCategorySelect() {
        categoryApi({ status: -1, type: 1 }).then(res => {
          this.merCateList = res
          this.merCateList.map(item => {
            this.$set(item , 'disabled', true)
          })
        })
      },
      getInfo(){
        this.loading = true
        couponInfoApi({id: this.$route.params.id}).then(res => {
          const info = res.coupon
          this.ruleForm = {
            useType: info.useType,
            fixedTime: info.fixedTime,
            isForever: info.isForever,
            name: info.name,
            money: info.money,
            minPrice: info.minPrice,
            day: info.day,
            type: info.type,
            limitness: info.limitness,
            sort: info.sort,
            total: info.total,
            status: info.status,
            primaryKey: Number(info.primaryKey),
            checked: res.product || [],
            menkan:res.menkan,
          }
          this.loading = false
        }).catch(res => {
          this.loading = false
          this.$message.error(res.message)
        })
      },
      handleRemove (i) {
        this.ruleForm.checked.splice(i, 1)
      },
      //导入商品
    getStoreItem(row){
         console.log("147",row)
         this.ruleForm.checked=row
         this.modals=false
      },
      // changeGood(){
      //   const _this = this
      //   this.$modalGoodList(function(row) {
      //     console.log("shangpin",row)
      //     _this.ruleForm.checked = row
      //   },'many',_this.ruleForm.checked)
      // },
      submitForm:Debounce(function(formName) {
      //  if( (this.ruleForm.fixedTime && !this.termTime) || this.ruleForm.fixedTime && !this.termTime.length) return this.$message.warning("请选择使用有效期限")
      //  if( (this.ruleForm.isForever && !this.isForeverTime) || (this.ruleForm.isForever && !this.isForeverTime.length)) return this.$message.warning("请选择请选择领取时间")
      //   if( this.ruleForm.useType === 2 ) this.ruleForm.primaryKey = this.ruleForm.checked.map(item => {return item.id}).join(',')
      //   if( this.ruleForm.useType === 1 ) this.ruleForm.primaryKey = ''
      //   if( !this.threshold ) this.ruleForm.minPrice = 0
      //   if( !this.ruleForm.limitness ) this.ruleForm.total = 0
        this.ruleForm.fixedTime  ? (this.ruleForm.useStartTime = this.ruleForm.time[0], this.ruleForm.day = null) : this.ruleForm.useStartTime = ''
        this.ruleForm.fixedTime  ? (this.ruleForm.useEndTime = this.ruleForm.time[1], this.ruleForm.day = null) : this.ruleForm.useEndTime = ''
       this.ruleForm.receiveStartTime = this.ruleForm.revetime[0]
      this.ruleForm.receiveEndTime = this.ruleForm.revetime[1]
      if (this.ruleForm.useType == 0) {
            this.ruleForm.caseIds = "";
          }else if(this.ruleForm.useType == 1){
            let list=[]
            this.ruleForm.checked.map(item=>{
              list.push(item.id)
            })
            this.ruleForm.caseIds = list.join(","); 
          }else{
            this.ruleForm.caseIds = this.ruleForm.primaryKey
          }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('优惠劵创建后将不可修改，是否确认提交?').then(() => {
          this.loading = true
            couponSaveApi(this.ruleForm).then(() => {
              this.$message.success("新增成功")
              this.loading = false
              setTimeout(() => {
                this.$router.push({ path: `/marketing/coupon/list` })
              }, 200);
            }).catch(() => {
              this.loading = false
            })
        })
           
          } else {
            this.loading = false
            return false;
          }
        });
      }),
      
    }
  }
</script>

<style scoped lang="scss">
  .pictrue{
    width: 60px;
    height: 60px;
    border: 1px dotted rgba(0,0,0,0.1);
    margin-right: 10px;
    position: relative;
    cursor: pointer;
    img{
      width: 100%;
      height: 100%;
    }
  }
  .btndel{
    position: absolute;
    z-index: 1;
    width :20px !important;
    height: 20px !important;
    left: 46px;
    top: -4px;
  }
</style>
